﻿using System; 
using System.Collections.Generic;
using System.Text; 
using UnityEditor;
using UnityEditor.IMGUI.Controls; 
using UnityEngine;
using XFABManager;

namespace XFGameFramework.Localization
{

    internal class IconGUIContent
    {
        public string projectName;
        public string iconName;
        public GUIContent content;
    }

    public class LanguageListTree : DragableTreeView<LanguageConfig>
    {

        private MultiLanguageConfigs multiLanguageConfig;

        private bool isContextClickItem;
         
        private Rect name_rect; 

        private Dictionary<int, IconGUIContent> contents = new Dictionary<int, IconGUIContent>();
        
        public MultiLanguageConfigs MultiLanguageConfig => multiLanguageConfig;


#if UNITY_6000_2_OR_NEWER  
        public LanguageListTree(TreeViewState<int> state, MultiLanguageConfigs multiLanguageConfig) : base(multiLanguageConfig, multiLanguageConfig.Languages,state)
#else
        public LanguageListTree(TreeViewState state, MultiLanguageConfigs multiLanguageConfig) : base(multiLanguageConfig, multiLanguageConfig.Languages,state)
#endif

        {
            this.multiLanguageConfig = multiLanguageConfig;
            showBorder = true;  
            rowHeight = 25;

            Reload();
        }

        // Fix编码
#if UNITY_6000_2_OR_NEWER
        protected override void OnBuildRoot(TreeViewItem<int> root, IList<LanguageConfig> datas)
#else
        protected override void OnBuildRoot(TreeViewItem root, IList<LanguageConfig> datas)
#endif

        {
            base.OnBuildRoot(root, datas);
            contents.Clear();

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < multiLanguageConfig.Languages.Count; i++)
            {
                LanguageConfig info = multiLanguageConfig.Languages[i];
                if (info == null) continue;

                builder.Clear();

                if (info.language.ToString().Equals("Hugarian"))
                    builder.Append("Hungarian");
                else
                    builder.Append(info.language);

                if (!string.IsNullOrEmpty(info.displayName))
                {
                    builder.Append("(").Append(info.displayName).Append(")");
                }

                int id = (int)info.language;

#if UNITY_6000_2_OR_NEWER
                TreeViewItem<int> child = new TreeViewItem<int>(id, 0, builder.ToString());
#else
                TreeViewItem child = new TreeViewItem(id, 0, builder.ToString());
#endif

                root.AddChild(child);
            }

        }
         
        protected override void RowGUI(RowGUIArgs args)
        { 
            name_rect.Set(args.rowRect.height, args.rowRect.y, args.rowRect.width - args.rowRect.height - 25, args.rowRect.height);
              
            EditorGUI.LabelField(name_rect,args.item.displayName);
             
            if ((int)LocalizationManager.Language == args.item.id) 
            {
                name_rect.Set(args.rowRect.width - 25, args.rowRect.y, 25, args.rowRect.height);

                EditorGUI.LabelField(name_rect, EditorGUIUtility.IconContent("TestPassed"));
            }

            GUI.Box(args.rowRect, string.Empty, "CN Box");
        }

#if UNITY_6000_2_OR_NEWER
        protected override bool CanMultiSelect(TreeViewItem<int> item)
#else
        protected override bool CanMultiSelect(TreeViewItem item)
#endif

        {
            return true;
        }

        protected override void ContextClicked()
        {
            base.ContextClicked();

            if (isContextClickItem)
            {
                isContextClickItem = false;
                return;
            }

            GenericMenu menu = new GenericMenu();
            CreateLanuageConfig(menu);
        }

        protected override void ContextClickedItem(int id)
        {
            base.ContextClickedItem(id);
            isContextClickItem = true;

            GenericMenu menu = new GenericMenu();
            menu.AddItem(new GUIContent("删除"), false, () =>
            {
                foreach (var item in GetSelection())
                {
                    DeleteLanguages((SystemLanguage)item);
                }

                SetSelection(new int[0]);
            });

            menu.AddSeparator(string.Empty); 
            CreateLanuageConfig(menu); 
        }

#if UNITY_6000_2_OR_NEWER
        protected override IList<TreeViewItem<int>> BuildRows(TreeViewItem<int> root)
        {
            return base.BuildRows(root);
        }
#else
        protected override IList<TreeViewItem> BuildRows(TreeViewItem root)
        {
            return base.BuildRows(root);
        }
#endif



        private void CreateLanuageConfig(SystemLanguage language)
        {
            if (multiLanguageConfig == null) return;

            MultiLanguageConfigs config = multiLanguageConfig;
            if (config == null) return;
            string asset_path = AssetDatabase.GetAssetPath(config);
            string guid = AssetDatabase.AssetPathToGUID(asset_path);

            LanguageConfig last = null;

            for (int i = 0; i < config.Languages.Count; i++)
            {
                if (config.Languages[0] == null)
                    continue;

                last = config.Languages[i];
                break;
            }

            LanguageConfig languageConfig = ScriptableObject.CreateInstance<LanguageConfig>();
            languageConfig.language = language;

            if (last != null) 
            {
                // 同步语言配置 
                foreach (var item in last.languagesInfo)
                {
                    LanguageInfo info = new LanguageInfo();
                    info.id = item.id;
                    info.type = item.type;
                    languageConfig.languagesInfo.Add(info);
                } 
            }


            string path = string.Format("Assets/Extensions/Localization/{0}", guid);
             
            MultiLanguageConfigsController.CreateAsset(languageConfig, path, false);

            config.Languages.Add(languageConfig);
            EditorUtility.SetDirty(config);
            config.ClearCache();
            languageConfig.Rename();
            EditorUtility.SetDirty(languageConfig);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            Reload();
        }
         
        private void CreateLanuageConfig(GenericMenu menu)
        {

            string[] names = Enum.GetNames(typeof(SystemLanguage));
             
            foreach (string name in names)
            {
                string n = name;
                if (n.Equals("Hugarian"))
                    n = "Hungarian";
                 
                SystemLanguage l = (SystemLanguage)Enum.Parse(typeof(SystemLanguage), n);
                  
                LanguageConfig language = multiLanguageConfig.GetLanguageConfigData(l);

                string displayName = l.ToString();

                if (displayName.Equals("Hugarian"))
                    displayName = "Hungarian";

                if (language == null)
                {
                    menu.AddItem(new GUIContent(displayName), false, () => 
                    { 
                        CreateLanuageConfig(l);
                    });
                }
                else 
                    menu.AddDisabledItem(new GUIContent(displayName), true); 
            }

            menu.ShowAsContext();
        }

        private void DeleteLanguages(SystemLanguage language)
        {
            if (multiLanguageConfig == null)
                return;

            LanguageConfig data = multiLanguageConfig.GetLanguageConfigData(language);
            if (data == null) return;

            AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(data));
            multiLanguageConfig.Languages.Remove(data);
            multiLanguageConfig.ClearCache();
            EditorUtility.SetDirty(multiLanguageConfig);
            AssetDatabase.SaveAssets();
            Reload();
        }

        protected override void RefreshDatas()
        {
            base.RefreshDatas();

            if(multiLanguageConfig)
                multiLanguageConfig.ClearCache();
        }

    }
}

